package org.csu.mypetstore.web.servlets.Ajax;

import com.alibaba.fastjson.JSON;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;

public class CartUpdateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session= req.getSession();
        Cart cart = (Cart)session.getAttribute("cart");
//        Iterator<CartItem> cartItemIterator = cart.getAllCartItems();
//
        int quantity= Integer.parseInt(req.getParameter("quantity"));
        int itemNum= Integer.parseInt(req.getParameter("itemNum"));

        cart.getCartItemList().get(itemNum).setQuantity(quantity);
//        while(cartItemIterator.hasNext()){
//            CartItem cartItem= (CartItem) cartItemIterator.next();
//            String itemId= cartItem.getItem().getItemId();
//
//            System.out.println(req.getParameter("quantity") + "123");
//
//            int quantity= Integer.parseInt((String) req.getParameter("quantity"));
//            cart.setQuantityByItemId(itemId, quantity);
//            if(quantity<1)
//                cartItemIterator.remove();
//        }
        session.setAttribute("cart", cart);

//        Cart cart1= (Cart) session.getAttribute("cart");
//        Iterator<CartItem> cartItemIterator1 = cart1.getAllCartItems();
//        String quantityAll= "";
//        while (cartItemIterator1.hasNext()){
//            CartItem cartItem= (CartItem) cartItemIterator1.next();
//            int quantity= cartItem.getQuantity();
//            quantityAll += quantity+ "," + cartItem.getTotal() + "," + cart1.getSubTotal();
//
//        }
        String quantityAll= "";
        quantityAll+= quantity + "," + cart.getCartItemList().get(itemNum).getTotal()+ "," +cart.getSubTotal();
        resp.setContentType("text/plain");
        System.out.println(quantityAll);
        PrintWriter out= resp.getWriter();
        out.print(quantityAll);

        out.flush();
        out.close();
    }
}
